package com.pikaqiu.warehouse.interceptor;

import com.pikaqiu.warehouse.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * @Author: Administrator
 * @Date: 2024/7/26
 */
@Slf4j
@Component
public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 打印请求信息
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        String headers = Collections.list(request.getHeaderNames()).stream()
                .map(headerName -> headerName + ": " + request.getHeader(headerName))
                .collect(Collectors.joining(", "));
        String parameters = request.getParameterMap().entrySet().stream()
                .map(entry -> entry.getKey() + "=" + Arrays.toString(entry.getValue()))
                .collect(Collectors.joining(", "));
        request.setAttribute("logStartTime", System.currentTimeMillis());
        String ip = HttpUtils.getRealIp(request);
        log.info("\nIP: {}\n请求地址: {}\n请求方式: {}\n请求参数: {}\n请求头: {}\n请求体：{}", ip, uri, method,
            queryString, headers, parameters);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime = (Long) request.getAttribute("logStartTime");
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        log.info("请求 [{}] {} 耗时 {} ms", request.getMethod(), request.getRequestURI(), duration);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
    }
}
